package com.zhangye.test.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhangye.test.mapper.AccountMapper;
import com.zhangye.test.mapper.AccountPayMapper;
import com.zhangye.test.mapper.AlipayOrderInfoMapper;
import com.zhangye.test.model.Account;
import com.zhangye.test.model.AccountPay;
import com.zhangye.test.model.AlipayOrderInfo;
import com.zhangye.test.util.Arith;
import com.zhangye.test.util.OrderInfoUtil2_0;
import com.zhangye.test.util.RSA;
import com.zhangye.test.util.SignUtils;
import com.zhangye.test.util.StringUtils;

@Service
public class AliPayAsyncServices {

	Logger logger = LoggerFactory.getLogger(AliPayAsyncServices.class);
			
	@Autowired
	private AlipayOrderInfoMapper aliPayOrderInfoMapper;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private AccountPayMapper accountPayMapper;
	
	public String async(Map<String, String> param ,Map<String, String> sign) throws ParseException {

		Account ac;
		AccountPay acp;
		AlipayOrderInfo ap;
		String  result = "failure";
		double total_amount = Double.parseDouble((String) param.get("total_amount"));
		String ALIPAY_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWa"
				+ "JMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB";
		String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7oE9AWXmLPrahIVMXR6+372Vee8MChKY4ywm4gXj4mtG45G3qQCOkbm8dz9ktjfqsUsh+LOKUbmKHtolOkDgxLeIe"
				+ "515mV56Lzo9qTiHZaTzEkOyDoZ1YnhmknP/pN/9QVQcvEKXb57PVzLTegAl1ZDrdYFVzxKLTAGNHgYE9MwIDAQAB";
		
		StringBuilder key = OrderInfoUtil2_0.sort(param);
		String oriSign = SignUtils.sign(key.toString(), ALIPAY_PUBLIC_KEY);
		String encodedSign = "";
		try {
			encodedSign = URLEncoder.encode(oriSign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		//验证签名是否合法
		if (RSA.verify(param.toString(), sign.get("sign"))) {
			String where = " and outTradeNo = '" + param.get("out_trade_no") + "'";
			where += " and totalAmount = " + total_amount;
			List<AlipayOrderInfo> list = aliPayOrderInfoMapper.selectByWhere(where);
			if (list.size() == 1) {
				if (param.get("seller_id").equals("2088421943565793")) {
					if (param.get("app_id").equals("2018060560269652")) {
						if (param.get("trade_status").equals("TRADE_FINISHED")
								|| param.get("trade_status").equals("TRADE_SUCCESS")) {
							// 更新account表
							if (Arith.compareTo(total_amount, 0.1) >= 0) {
								double acto = Arith.mul(total_amount, 0.1);//赠送金额
								total_amount = Arith.add(total_amount, acto);
							}
							ac = new Account();
							double balance = 0;
							int a = 0;
							String where2 = " and userId = '" + list.get(0).getUserid() + "'";
							List<Account> account = accountMapper.selectByWhere(where2);
							if (account.size() > 0) {
								balance = account.get(0).getBalance();
								ac.setUserid(list.get(0).getUserid());
								ac.setBalance(balance+Double.valueOf(total_amount));
								ac.setVariation("+"+total_amount);
								ac.setUpdatetime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
								a = accountMapper.updateByPrimaryKey(ac);
							} else {
								ac.setUserid(list.get(0).getUserid());
								ac.setInserttime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
								ac.setBalance(Double.valueOf(total_amount));
								ac.setVariation("+"+total_amount);
								a = accountMapper.insert(ac);
							}
							if (a == 1) {
								acp = new AccountPay();
								acp.setUserid(list.get(0).getUserid());
								acp.setInserttime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
								acp.setTotalamount(Double.valueOf(total_amount));
								acp.setBalance(balance+Double.valueOf(total_amount));
								acp.setVariation("+"+total_amount);
								acp.setPayway("支付宝支付");
								acp.setOuttradeno(param.get("out_trade_no").toString());
								acp.setDeletelogo(0);
								int i = accountPayMapper.insert(acp);
								if (i > 0) {
									logger.info("交易成功，插入account_pay表失败，订单号：" + param.get("out_trade_no"));
								}
							} else {
								logger.info("交易成功，插入account表失败，订单号：" + param.get("out_trade_no"));
							}
							
							//更新aliPay_orderInfo表
							ap = new AlipayOrderInfo();
							ap.setUpdatetime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
							ap.setTradeno(param.get("trade_no"));
							ap.setTradestatus(param.get("trade_status"));
							int i = aliPayOrderInfoMapper.updateByPrimaryKey(ap);
							if (i == 0) {
								logger.info("aliPay_orderInfo表更新失败，订单号：" + param.get("out_trade_no"));
							}
							result = "success";
						}
					}
				}
			}
		} else {
			logger.info("签名验证失败，订单号：" + param.get("out_trade_no"));
		}
		return result;
	}
	
}
